package main;

import book.BookList;
import book.Book;
import exception.PassWordException;
import exception.UserNameException;
import user.AdminUser;
import user.NormalUser;
import user.User;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static User login(String name, String password) throws PassWordException, UserNameException {
        try {
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入你的用户名：");
            String userName = scanner.nextLine();
            //判断用户名是否正确
            if(!userName.equals(name)){
                throw new UserNameException("用户名错误....");
            }
            System.out.println("请输入你的密码：");
            String passWord = scanner.nextLine();
            //判断密码是否正确
            if(!passWord.equals(password)){
                throw new PassWordException("密码错误....");
            }
            System.out.println("请输入你的身份：1.管理员  2.普通用户");
            int choice = scanner.nextInt();

            if(choice == 1){
                return new AdminUser(name,passWord);
            }else {
                return new NormalUser(name,passWord);
            }
        } catch (UserNameException e) {
            e.printStackTrace();
        } catch (PassWordException e) {
            e.printStackTrace();
        }

        return null;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        //注册
        System.out.println("请设置你的用户名：");
        String name = sc.nextLine();
        System.out.println("请设置你的密码：");
        String password = sc.nextLine();
        System.out.println("恭喜注册成功！！！");
        System.out.println("=================");

        // 从文件读取书籍信息
        Book[] bookArray = readBooksFromFile("books.txt");

        int choice = 1;
        int n = 1;
        BookList bookList = new BookList(bookArray);
        User user = login(name, password);
        while (n == 1){
            choice = user.menu();
            user.doIoperation(choice,bookList);
            System.out.println("是否继续进行操作（Yes输入1/No输入0）：");
            n = sc.nextInt();
        }

        // 程序结束后，将书籍信息写入文件
        writeBooksToFile(bookList, "books.txt");
        System.out.println("书籍信息已保存到 books.txt 文件中");
    }

    // 从文件读取书籍信息的方法
    public static Book[] readBooksFromFile(String filename) {
        List<Book> bookList = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                //默认书籍为未借阅
                if (parts.length >= 4) {
                    String name = parts[0].trim();
                    String author = parts[1].trim();
                    int price = Integer.parseInt(parts[2].trim());
                    String type = parts[3].trim();

                    // 检查是否有借阅状态信息
                    boolean isborrow = false;
                    if (parts.length >= 5) {
                        String borrowStatus = parts[4].trim();
                        isborrow = borrowStatus.equals("已借出") || borrowStatus.equals("true");
                    }
                    Book book = new Book(name, author, price, type, isborrow);
                    bookList.add(book);
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件 " + filename + " 不存在，将使用默认书籍信息");
            // 如果文件不存在，创建默认的书籍信息
            bookList.add(new Book("三国演义", "罗贯中", 10, "小说", false));
            bookList.add(new Book("西游记", "吴承恩", 20, "小说", false));
            bookList.add(new Book("红楼梦", "曹雪芹", 18, "小说", false));
        } catch (IOException e) {
            System.out.println("读取文件时发生错误: " + e.getMessage());
        }

        return bookList.toArray(new Book[0]);
    }

    // 将书籍信息写入文件的方法
    public static void writeBooksToFile(BookList bookList, String filename) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(filename))) {
            for (int i = 0; i < bookList.getUsedsize(); i++) {
                Book book = bookList.getBook(i);
                if (book != null) {
                    writer.println(book.getName() + "," + book.getAuthor() + "," +
                            book.getPrice() + "," + book.getType() + "," +
                            (book.isIsborrow() ? "已借出" : "未借出"));
                }
            }
        } catch (IOException e) {
            System.out.println("写入文件时发生错误: " + e.getMessage());
        }
    }
}